package com.fone.player.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.TextUtils;
import android.widget.RemoteViews;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.QntRst;
import com.fone.player.client.QntRst.Cnt;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.Download;
import com.fone.player.entity.NotificationBean;
import com.fone.player.storage.StorageModule;
import com.fone.player.storage.download.DownloadAppManager;
import com.fone.player.storage.download.NotificationHandle;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;

/**
 * 通知处理逻辑
 * 
 * @author JasonZue
 * @since 2014-5-20
 */
@SuppressLint("SimpleDateFormat")
@SuppressWarnings("unused")
public class NotificationHandler {
	private static String TAG = NotificationHandler.class.getSimpleName();

	private final static byte[] _taskLock = new byte[0];
	
	private static final String classname = "com.fone.player";
//	private static boolean clear_default = false;
	
	// 请求失败后时间
	private static final long NUM1 = 9 * 1000;
	private static final long NUM2 = 81 * 1000;
	private static final long NUM3 = 243 * 1000;
	private static final long NUM4 = 729 * 1000;
	private static final long NUM5 = 2187 * 1000;
	private static final long NUM6 = 6561 * 1000;
	private static final long DEFAULTNUM = 7200 * 1000;
//	private static final long NUM7 = 19683 * 1000;
//	private static final long NUM8 = 59049 * 1000;
//	private static final long NUM9 = 177147 * 1000;

	// 链接类型
	private static final int FULLSCREEN = 0; // 全屏页
	private static final int DETAILVIEW = 1; // 详情页
	private static final int POSTERVIEW = 2; //
	private static final int WAP = 3; // 打开wap网页
	private static final int DOWNLOADSOFT = 4; // 下载应用
	private static final int FEEPAGE = 5; // 计费页面
	// private static final int FEEDBACK = 6; // 评论列表
	private static final int PROGRAM = 7; // 栏目页
	private static final int WEBVIEW = 8;// 打开原始网页
	private static final int FEEDBACK = 9; // 反馈回复
	private static final int NOTIFITIONVIEW = 10; // 消息列表

	// 通知类型
	private static final int FEEDBACKTYPE = 6; // 评论列表

	private static final String NOTIFICATION = "notification";//请求通知周期
	private static final String CLEARDEFAULT = "clear_default";//清除默认周期

	private static final int NETWORKERROR_NUM = 1; // 网络异常
	private static final int NOTIFICATION_UPDATE_NUM = 2;// 更新通知

	private static final String NOTICATION_EXACT_TIME = "notificaion_exact_time";// 请求通知时间

	private static final String CLEAR_DEFAULT_EXACT_TIME = "clear_default_exact_time";// 清楚默认时间
	
	public static final String CLEAR_AUTO_FLAG = "clear_auto_flag";//清除默认开关
	
	private long sNotificationTime = 3L * 1000; //请求通知周期
	
	private long CleardeFaultSettingCycletime = 10l * 60 * 1000;//清除默认周期
	
	

	private Context mContext;
	private int numCount = 0;// 请求失败计数

	private boolean isRequestSuccess = false;
	// 广播
	private IntentFilter timerBrocastIntentFilter = null;
	private IntentFilter sendNotifiBrocastIntentFilter = null;

	private SharedPreferences sPreferences, mSp;
	private NotificationManager nm;

	private BroadcastReceiver timerBrocast = null;
	private BroadcastReceiver sendNotifiBrocast = null;

	private NotificationCallback callback;
	
//	private AlarmManager am;
//	private PendingIntent alarmIntent;
	
	
//	public static final String CHECK_TIME_ACTION = "com.fone.player.notification.checkTimeAction";
	
	
	private StringBuilder log = new StringBuilder();

	public NotificationHandler(Context mContext) {
		super();
		this.mContext = mContext;
		nm = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		sPreferences = mContext.getSharedPreferences("notificationService",
				Context.MODE_PRIVATE);
		callback = new NotificationCallback();
	}

	/**
	 * 开启通知
	 */
	public void startNotification() {
		L.v(TAG, "NotificationHandler>>startNotification>");

		FoneUtil.writeNotificationLog("通知服务开启");
		
		registerSendNotificationBrocast();
		registerTimerBrocast();
		
//		am = (AlarmManager)ApplicationManage.getGlobalContext().getSystemService(Context.ALARM_SERVICE);
//        Intent intent = new Intent(CHECK_TIME_ACTION);
//        alarmIntent = PendingIntent.getBroadcast(ApplicationManage.getGlobalContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+30000, 60000, alarmIntent);
        

		long initNotificationTime = getLong(NOTICATION_EXACT_TIME, 0);
		long initClearDefaultTime = getLong(CLEAR_DEFAULT_EXACT_TIME, 0);

		if (initNotificationTime == 0) {
			sNotificationTime = 3L * 1000;
			putLong(NOTIFICATION, sNotificationTime);
			L.v(TAG, "NotificationHandler>>startNotification>notificationTime"
					+ sNotificationTime);
			measureTime(sNotificationTime,0,true);
		}else{
			sNotificationTime = getLong(NOTIFICATION, 3L * 1000);
		}
		
		if(initClearDefaultTime == 0){
			CleardeFaultSettingCycletime = 10L * 60 * 1000;
			putLong(CLEARDEFAULT, CleardeFaultSettingCycletime);
			L.v(TAG, "NotificationHandler>>startNotification>CleardeFaultSettingTime"
					+ CleardeFaultSettingCycletime);
			measureTime(CleardeFaultSettingCycletime,0,false);
		}else{
			CleardeFaultSettingCycletime = getLong(CLEARDEFAULT, 10L * 1000);
		}
		
	}

	/**
	 * 关闭通知
	 */
	public void stopNotification() {
		L.v(TAG, "NotificationHandler>>stopNotification>");
		FoneUtil.writeNotificationLog("通知服务关闭");
//		if(am!=null){
//			am.cancel(alarmIntent);
//			am = null;
//		}
		if (sendNotifiBrocast != null) {
			mContext.unregisterReceiver(sendNotifiBrocast);
			sendNotifiBrocast = null;
			L.v(TAG, "NotificationHandler>>registerTimerBrocast>stop " + sendNotifiBrocast);
		}
		if (timerBrocast != null) {
			mContext.unregisterReceiver(timerBrocast);
			timerBrocast = null;
			L.v(TAG, "NotificationHandler>>registerTimerBrocast>stop " + timerBrocast);
		}
		putLong(NOTICATION_EXACT_TIME, 0);
		putLong(CLEAR_DEFAULT_EXACT_TIME, 0);
	}

	/**
	 * 注册系统time_tick广播 循环访问服务器
	 */
	public void registerTimerBrocast() {
		L.v(TAG, "NotificationHandler>>registerTimerBrocast");
		if (null == timerBrocastIntentFilter) {
			timerBrocastIntentFilter = new IntentFilter();
			timerBrocastIntentFilter.addAction(Intent.ACTION_TIME_TICK);
//			timerBrocastIntentFilter.addAction(CHECK_TIME_ACTION);
		}

		if (null == timerBrocast) {
			timerBrocast = new BroadcastReceiver() {
				@SuppressLint("SimpleDateFormat")
				@Override
				public void onReceive(Context context, Intent intent) {
					
					L.v(TAG,"timerBrocast"," onReceive start !!!");

					// 如果存在没有发送到系统栏的通知，就发送
//					synchronized (_taskLock){
//						if(isSendTime()){
//							new Thread(){
//								public void run() {
//									ArrayList<NotificationBean> list = StorageModule.getInstance().getNotificationListByIsShow(false);
//									mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
//									boolean notificationFlag = mSp.getBoolean(FoneConstant.NOTIFY_SWITCH_FLAG_SP, true);
//									L.v(TAG, "timerBrocast onReceive","notification is open : " + notificationFlag);// 通知开关是否打开
//									if(list==null){
//										return;
//									}
//									for (NotificationBean notificationBean : list) {
//										notificationBean.setNotificationIsShow(true);
//										if(!notificationFlag){
//											//发送通知
//											Bitmap iconImage = null;
//											if (notificationBean.getNotificationContentPatternType() == 1 
//													&& notificationBean.getNotificationIconUrl() != null) {
//												iconImage = getIconImage(notificationBean.getNotificationIconUrl());
//											}
//											sendNotification(notificationBean,iconImage);
//										}
//									}
//									//更新数据库
//									StorageModule.getInstance().updateNotificationIsShow(list);
//								};
//							}.start();
//						}
//					}
					
					// 清除默认设置
					if (System.currentTimeMillis() >= getLong(
							CLEAR_DEFAULT_EXACT_TIME, System.currentTimeMillis() + 1)) {
						L.v(TAG, "BroadcastReceiver", ">>>>>>>>>>>> enter clear_default_");
						clearDefault();
						measureTime(CleardeFaultSettingCycletime, 0,false);
					}
					// 向服务器请求通知
					requestNotification();
				}
			};
			mContext.registerReceiver(timerBrocast, timerBrocastIntentFilter);
		}
	}
	
	
	public void registerSendNotificationBrocast(){
		
		L.v(TAG, "NotificationHandler>>registerSendNotificationBrocast");
		if (null == sendNotifiBrocastIntentFilter) {
			sendNotifiBrocastIntentFilter = new IntentFilter();
			sendNotifiBrocastIntentFilter.addAction(NotificationReceiver.NOTIFICATION_NOTIFICATION_CHECKSEND);
			sendNotifiBrocastIntentFilter.addAction(NotificationReceiver.NOTIFICATION_DOWNLOADSOFT);
			sendNotifiBrocastIntentFilter.setPriority(900);
		}
		
		if(sendNotifiBrocast == null){
			sendNotifiBrocast = new BroadcastReceiver(){
				@Override
				public void onReceive(Context context, Intent intent) {
					
					if(NotificationReceiver.NOTIFICATION_NOTIFICATION_CHECKSEND.equals(intent.getAction())){
						final ArrayList<NotificationBean> notificationList = intent.getParcelableArrayListExtra(NotificationReceiver.NOTIFICATION_INFO);
						
						FoneUtil.writeNotificationLog("NotificationHandler  BroadcastReceiver  收到广播 , 判断是否在发送时间 ");
						// 是否在 早8点  到 晚10点 
						if(isSendTime()){
							new Thread(){
								@Override
								public void run() {
									
									L.v(TAG, "NotificationCallback  onSuccess "," sendMessage start -------- ");
									// 是   
									int needReportOutNum = 0; //外部通知上报数量
									int needReportinNum = 0; //内部通知上报数量
									for (NotificationBean notificationBean : notificationList) {
										
										L.v(TAG, "registerSendNotificationBrocast onReceive", "notificationBean is not null :"+ notificationBean!=null);
										notificationBean.setNotificationIsShow(true);
										//如果通知开关打开 发送通知
										mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
										boolean notificationFlag = mSp.getBoolean(FoneConstant.NOTIFY_SWITCH_FLAG_SP, true);
										L.v(TAG, "sendNotifiBrocast onReceive","notification is open : " + notificationFlag);
										FoneUtil.writeNotificationLog("在发送外通知时间区域  外通知开关是否打开 : " + notificationFlag);
										if(notificationFlag){
											//获取图片
											Bitmap iconImage = null;
											if (notificationBean.getNotificationContentPatternType() == 1 
													&& notificationBean.getNotificationIconUrl() != null) {
												iconImage = getIconImage(notificationBean.getNotificationIconUrl());
											}
											if(notificationBean.getNotificationType() == NotificationBean.NOTIFICATION_TYPE){
												needReportOutNum ++; //如果是通知 添加上报数量
											}
											sendNotification(notificationBean,iconImage);
										}
										
										//插入数据库
										L.i(TAG, notificationBean.toString());
										int addNotification = StorageModule.getInstance().addNotification(notificationBean);
										L.v(TAG, "NotificationCallback  onSuccess "," sendMessage end -------- "+addNotification);
										if(notificationBean.getNotificationType() == NotificationBean.NOTIFICATION_TYPE && addNotification!=-1){
											needReportinNum ++;
										}
										
									}
									//上报外部通知
									FoneUtil.reportNotification(9, needReportOutNum,notificationList);
									//上报内部部通知
									FoneUtil.reportNotification(8, needReportinNum,notificationList);
								};
							}.start();
						}else{
							//写入文件
							FoneUtil.writeNotificationLog("当前时间: " + FoneUtil.getTime() + " 0点 - 7点  不发送外通知 ");
							int needReportinNum = 0;
							for (NotificationBean notificationBean : notificationList) {
								L.v(TAG, "NotificationCallback  onSuccess "," not sendtime start -------- ");
								// 否   插入数据库 
								notificationBean.setNotificationIsShow(true);
								int addNotification = StorageModule.getInstance().addNotification(notificationBean);
								L.v(TAG, "NotificationCallback  onSuccess "," not sendtime end -------- "+addNotification);
								if(notificationBean.getNotificationType() == NotificationBean.NOTIFICATION_TYPE && addNotification!=-1){
									needReportinNum ++; //如果是通知 添加上报数量
								}
							}
							//上报内部通知
							FoneUtil.reportNotification(8, needReportinNum, notificationList);
						}
						abortBroadcast();//中断广播
					}else if(NotificationReceiver.NOTIFICATION_DOWNLOADSOFT.equals(intent.getAction())){
						
						NotificationBean notificationBean = (NotificationBean)intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
						//更改阅读状态
						notificationBean.setNotificationIsRead(true);
						StorageModule.getInstance().updateNotificationIsRead(notificationBean);
						//下载
						String downloadUrl = notificationBean.getNotificationUrl()+"&cipher="+Request.getInstance().getCipher();
						String downloadTitle = notificationBean.getNotificationName();
						
						L.v(TAG, "NOTIFICATION_DOWNLOADSOFT", " downloadUrl : " + downloadUrl);
						
						Download download = new Download();
						download.setDownloadIsShowRunningNotification(true);
						download.setDownloadUrl(downloadUrl);
						download.setDownloadFileName(downloadTitle);
						download.setDownloadNotification(ApplicationManage.getGlobalContext());
						download.setDownloadIsInstall(true);
						download.setDownloadIsErrorToast(true);
						download.setDownloadIsLimitSpeed(false);
						download.setDownloadType(Download.DOWNLOAD_RECOMMEND);
						
						NotificationHandle.init(mContext);
						DownloadAppManager.getInstance().addDownloadFile(download);
						
					}
				}
			};
			mContext.registerReceiver(sendNotifiBrocast, sendNotifiBrocastIntentFilter);
		}
	}
	

	// 向服务器请求通知
	protected void requestNotification() {
		
		L.v(TAG,"requestNotification"," requestNotification start !!!");
		
		// 判断是否到达请求通知的时间
		long notificationTime = sPreferences.getLong(NOTICATION_EXACT_TIME,
				System.currentTimeMillis() + 1);
		
		//开发阶段log 
		String currentTime ="currentTime : " +  "当前时间: " + FoneUtil.getTime();
		L.v(TAG, "requestNotification", currentTime);
		
		String nextRequestTime = "  Next notificationTime : " + "下次请求时间: " 
					+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(notificationTime);
		L.v(TAG, "requestNotification", nextRequestTime);
		
		if(log.length()>0){
			log.delete(0, log.length());
		}
		log.append(currentTime);
		log.append(nextRequestTime);
		//TODO 写入文件
		FoneUtil.writeNotificationLog(log.toString());
		
		 if (notificationTime != 0
				&& System.currentTimeMillis() >= notificationTime
				 && FoneUtil.isNetOk(mContext)) {
			 String requestTime = "request notification time :  请求通知时间 : "+ FoneUtil.getTime();
			 L.v(TAG,"requestNotification",requestTime);
			 
			//TODO 写入文件
			 FoneUtil.writeNotificationLog(requestTime);
			 
			 //请求服务器 获取通知
			 Request.getNotifcationInstance(mContext).qnt(0,callback);
			 
			 Reporter.writeLog("Report on background task");
			 Reporter.start();
		 }
	}

	/**
	 * 获取网络返回日期附加的随机值
	 * 
	 * @param
	 * @return
	 */
	public long getRandomNumber(int range) {
		Random r = new Random();
		if (range != 0) {
			L.v(TAG, "NotificationHandler>>getRandomNumber>getRanage", ""
					+ range);
			return r.nextInt(range * 1000);
		}
		return 0;
	}

	/**
	 * 计算 下一次 请求服务器的时间
	 * 
	 * @param time
	 * @param isNotification
	 */
	public void measureTime(long time,long ranageFigure,boolean isNotification) {

		long delay = time + ranageFigure;
		
		Calendar canlender = Calendar.getInstance();
		canlender.setTimeInMillis(System.currentTimeMillis());
		canlender.add(Calendar.MILLISECOND, Long.valueOf(delay).intValue());

		long TimeInMillised = canlender.getTimeInMillis();

		int nowHour = canlender.get(Calendar.HOUR_OF_DAY);
		int nowMinute = canlender.get(Calendar.MINUTE);
		int nowday = canlender.get(Calendar.DATE);
		String timeStr = String.valueOf(nowday) + "日,"
				+ String.valueOf(nowHour) + "时," + String.valueOf(nowMinute)
				+ "分.";
		L.v(TAG, "NotificationHandler>>measureTime>timeStr:" + timeStr);

		if (isNotification) {
			putLong(NOTICATION_EXACT_TIME, TimeInMillised); // 存放请求通知的毫秒时间
		} else {
			putLong(CLEAR_DEFAULT_EXACT_TIME, TimeInMillised);
		}
	}

	/**
	 * 访问失败设置默认时间间隔
	 */
	private void setErrorTime() {
		numCount++;
		L.v(TAG, "NotificationHandler>>setErrorTime>numCount : " + numCount
				+ " isRequestSuccess : " + isRequestSuccess);
		if (!isRequestSuccess) {
			switch (numCount) {
			case 1:
				sNotificationTime = NUM1;
				break;
			case 2:
				sNotificationTime = NUM2;
				break;
			case 3:
				sNotificationTime = NUM3;
				break;
			case 4:
				sNotificationTime = NUM4;
				break;
			case 5:
				sNotificationTime = NUM5;
				break;
			case 6:
				sNotificationTime = NUM6;
				break;
//			case 7:
//				sNotificationTime = NUM7;
//				break;
//			case 8:
//				sNotificationTime = NUM8;
//				break;
//			case 9:
//				sNotificationTime = NUM9;
			default:
				sNotificationTime = DEFAULTNUM;
				break;
			}
		}
		L.v(TAG, "NotificationHandler>>setErrorTime>notificationTime :"
				+ sNotificationTime);
		measureTime(sNotificationTime,0,true);
	}

	/**
	 * 通知使用的 独立的sharedPreferences
	 * 
	 * @param key
	 * @param value
	 */
	public void putString(String key, String value) {
		if (sPreferences != null) {
			sPreferences.edit().putString(key, value).commit();
		}
	}

	public String getString(String key, String defValue) {
		String value = null;
		if (sPreferences != null) {
			value = sPreferences.getString(key, defValue);
		}
		return value;
	}

	private void putLong(String key, long value) {
		if (sPreferences != null) {
			sPreferences.edit().putLong(key, value).commit();
		}
	}

	private long getLong(String key, long defValue) {
		long value = 0;
		if (sPreferences != null) {
			value = sPreferences.getLong(key, defValue);
		}
		return value;
	}

	private void putBoolean(String key, boolean value) {
		if (sPreferences != null) {
			sPreferences.edit().putBoolean(key, value).commit();
		}
	}

	private class NotificationCallback implements Callback<QntRst> {

		@Override
		public void onSuccess(final QntRst t) {
			// TODO 修改通知操作
			String qntRest = FoneUtil.getTime() + "  QntRst : " + t.toString();
			L.v(TAG, "NotificationCallback onSuccess",qntRest);
			
			//TODO 写入文件 
			FoneUtil.writeNotificationLog(qntRest);
			
			if(t.result!=0){
				isRequestSuccess = false;
				setErrorTime();//请求通知失败,计算下一次请求时间
				return;
			}
			isRequestSuccess = true;
			numCount = 0;
			
			//是否关闭清除设置
			boolean isClearSettingOpen = t.clearstate == 1 ? true : false;
			L.v(TAG, "onSuccess", " t.clearstate : " + t.clearstate + "  " + isClearSettingOpen); 
			if(getClearDefaultFlag() != isClearSettingOpen){
				setClearDefualtFlag(isClearSettingOpen);
			}
			
			//如果服务端自启要求改变 则关闭服务
			boolean isAutoOpen = t.autostate == 1? true:false;
			L.v(TAG, "onSuccess", " t.autostate : " + t.autostate + "  " + isAutoOpen); 
			if(!isAutoOpen){
				mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
				Editor edit = mSp.edit();
				edit.putBoolean(FoneConstant.NOTIFY_AUTO_OPEN_FLAG_SP, isAutoOpen);
				edit.commit();
				FoneServiceManager.getFoneServiceManager(mContext).stopNotificationService();
				return;
			}
			
			
			// 计算下一次请求通知的时间
			long ranageFigure = getRandomNumber(FoneUtil.String2Integer(t.range));
			//根据服务器的周期更变  更变本地的访问周期  并计算下次访问时间
			if (FoneUtil.String2Long(t.swch) != 0
					&& FoneUtil.String2Long(t.swch) * 1000 != sNotificationTime) { 
				
				L.v(TAG, "GetNotification", "t.swch!=notificationTime: "
						+ FoneUtil.String2Long(t.swch)
						+ "   sNotificationTime:" + sNotificationTime);
				
				sNotificationTime = FoneUtil.String2Long(t.swch) * 1000;
				putLong(NOTIFICATION, sNotificationTime);
				
				L.v(TAG, "GetNotification", "notification_time: "
						+ sNotificationTime + "ranageFigure: " + ranageFigure
						+ " t.swch:" + t.swch);
				
				// 计算下次请求通知的时间
				measureTime(sNotificationTime,ranageFigure,true);
				
			} else {
				if (0 == FoneUtil.String2Integer(t.swch)) {
					// 服务器没有返回时间间隔 设置默认1个小时
					measureTime(3600 * 1000,ranageFigure,true);
				} else {
					measureTime(sNotificationTime,ranageFigure,true);
				}
			}
			
			//根据服务器的周期更变  更变清除默认设置周期
			if (FoneUtil.String2Long(t.swp) != 0
					&& FoneUtil.String2Long(t.swp) * 1000 != CleardeFaultSettingCycletime) { 
				
				L.v(TAG, "GetNotification", "t.swp!=CleardeFaultSettingCycletime: "
						+ FoneUtil.String2Long(t.swch)
						+ "   CleardeFaultSettingCycletime:" + CleardeFaultSettingCycletime);
				
				CleardeFaultSettingCycletime = FoneUtil.String2Long(t.swp) * 1000;
				putLong(CLEARDEFAULT, CleardeFaultSettingCycletime);
				
				// 计算下次清除默认的时间
				measureTime(CleardeFaultSettingCycletime,0,false);
				
			} else {
				if (0 == FoneUtil.String2Integer(t.swp)) {
					// 服务器没有返回时间间隔 设置默认1个小时
					measureTime(3600 * 1000,0,false);
				} else {
					measureTime(CleardeFaultSettingCycletime,0,false);
				}
			}
			
			
			//TODO 处理应用升级
			notificationUpdate(mContext, t);
			
			//初始化 和 发送通知
			sendNotifications(mContext, t);
		}

		@Override
		public void onFailure(Error error) {
			String errorMessage = FoneUtil.getTime() + "  isNetworkError :  网络超时 :  "
									+ error.isNetworkError() + " status : " + error.getStatus()
									+ " reason : " + error.getReason();
			L.v(TAG, "NotificationCallback onFailure", errorMessage);
			//TODO 写入文件
			FoneUtil.writeNotificationLog(errorMessage);
			
			isRequestSuccess = false;
			setErrorTime();//请求通知失败,计算下一次请求时间
		}
	}

	
	/**
	 * 处理通知升级
	 * @param mContext
	 * @param t
	 */
	public static void notificationUpdate(Context mContext ,QntRst t){
		L.v(TAG, "notificationUpdate", " notificationUpdate start !!! ");
		if(t.softupdate!=null && !TextUtils.isEmpty(t.softupdate.updateurl)){
			//TODO 静默升级
			L.v(TAG, "notificationUpdate", " init update !!! ");
			Download download = new Download();
			download.setDownloadFileName(t.softupdate.name);
			download.setDownloadDesc(t.softupdate.updatedesc);
			download.setDownloadIsShowRunningNotification(false);
			download.setDownloadIsShowFinishNotification(true);
			download.setDownloadUrl(t.softupdate.updateurl);
			download.setDownloadIsInstall(false);
			download.setDownloadIsErrorToast(false);
			download.setDownloadIsLimitSpeed(true);
			download.setDownloadType(Download.DOWNLOAD_UPGRADE);
			download.setDownloadNotification(mContext);
			StorageModule.getInstance().addFileDownload(download);
			L.v(TAG, "notificationUpdate", " update start !!! ");
		}
	}
	
	
	/**
	 * 初始化和发送
	 */
	public static void sendNotifications(final Context mContext ,final QntRst t){
		if(t.cnts==null||t.cnts.cntList==null||t.cnts.cntList.size()==0){
			L.v(TAG, "sendNotifications", "t.cnts = " + t.cnts + "  t.cnts.cntList = " + t.cnts.cntList);
			return;
		}
		final List<Cnt> cnts = t.cnts.cntList;
		
		FoneUtil.writeNotificationLog("sendNotifications  执行起点");
		L.v(TAG, "sendNotifications", "traverse notificationList ini and send !!! ");
		//另起线程 发送通知
		new Thread(){
			@Override
			public void run() {
				
				ArrayList<NotificationBean> notificationList = new ArrayList<NotificationBean>();
				
				int followsCount = 0;//通知中 追播剧的数量
				
				for (Cnt cnt : cnts) {
					
					String notificationId = cnt.id+"_"+cnt.qtp;
					//如果收到过 不加入消息队列
					if(isReceived(notificationId)){ 
						L.v(TAG, "sendNotifications", "  isReceived  is true ! ");
						
						//TODO 写入文件   重复通知
						String repeatNotification =  "重复下发通知   notificationId : " + notificationId + " name : " +  cnt.name;
						FoneUtil.writeNotificationLog(repeatNotification);
						
						continue;
					}
					
					NotificationBean notificationBean = new NotificationBean();
					notificationBean.setNotificationServerId(notificationId);//服务端id
					notificationBean.setNotificationName(cnt.name);//标题
					notificationBean.setNotificationContent(cnt.desc);//内容
					notificationBean.setNotificationContentPatternType(FoneUtil.String2Integer(cnt.type)); //内容展示形式
					notificationBean.setNotificationIconUrl(FoneUtil.getAbsoluteUrl(t.host, t.shost,cnt.pic));//通知显示图片
					notificationBean.setNotificationDefinitionType(cnt.dfnt);//清晰度
					notificationBean.setNotificationContentType(cnt.qtp);//通知类型
					notificationBean.setNotificationExternalType(cnt.utp);//连接类型
					if(cnt.utp==NotificationBean.NOTIFICATION_EXTERNAL_TYPE_PLAY
							||cnt.utp==NotificationBean.NOTIFICATION_EXTERNAL_TYPE_DETAIL
							||cnt.utp==NotificationBean.NOTIFICATION_EXTERNAL_TYPE_WEB){
						notificationBean.setNotificationType(NotificationBean.NOTIFICATION_TYPE);//通知
					}else{
						notificationBean.setNotificationType(NotificationBean.INFORMATION_TYPE);//消息
					}
					notificationBean.setNotificationIsShowDownloadButton(cnt.btndown==1);//下载按钮显示   (暂无用?)
					notificationBean.setNotificationIsShowPlayButton(cnt.btnply==1);//播放按钮显示  (暂无用?)
					notificationBean.setNotificationDramaName(cnt.dname);// 剧集名称
					notificationBean.setNotificationCommentReplyTime(cnt.time); //反馈回复时间 
					notificationBean.setNotificationFeedBackTime(cnt.fbtime); //反馈时间 
					notificationBean.setNotificationFeedBackDesc(cnt.fbdesc); //反馈内容
					notificationBean.setNotificationPlayType(cnt.toply);// 播放方式type
					notificationBean.setNotificationExternalUrl(cnt.ourl); //原始网页地址
					
					if(notificationBean.getNotificationExternalType() == WAP 
							|| notificationBean.getNotificationExternalType() == DOWNLOADSOFT){//如果是wap页 或者是 软件下载  绝对url
						notificationBean.setNotificationUrl(FoneUtil.getAbsoluteUrl(t.host, t.shost, cnt.url)); //指定参数url
					}else{
						notificationBean.setNotificationUrl(cnt.url); //指定参数url
					}
					
					notificationBean.setNotificationShareUrl(cnt.weibourl); // 分享url
					notificationBean.setNotificationIsRead(false); //是否已经
					notificationBean.setNotificationCreateTime(System.currentTimeMillis()); //通知下发时间
					
					
					if(notificationList.contains(notificationBean)){ //如果集合已经包含该通知
						L.v(TAG, "sendNotifications", " notificationList contains this notification !!! ");
						continue;
					}
					
					notificationList.add(notificationBean);//添加通知队列
					
					if(cnt.qtp == NotificationBean.NOTIFICATION_CONTENT_TYPE_HOT_DRAMA){//如果是追播剧,累计数量
						followsCount++;
					}
					
				}
				
				if(notificationList.size()>0){
					
					//发送广播 来 发送通知或刷新列表
					Intent intent = new Intent();
					intent.setAction(NotificationReceiver.NOTIFICATION_NOTIFICATION_CHECKSEND);
					intent.putExtra(NotificationReceiver.NOTIFICATION_INFO, notificationList);
					mContext.sendOrderedBroadcast(intent, null);
					
					FoneUtil.writeNotificationLog("sendNotifications  发送广播  判断是否在通知页面");
				}
				
				//更新追播剧的数量
				L.v(TAG, "sendNotifications" ," COLLETION_TV_UPDATE_COUNT count : " + followsCount);
				if(followsCount!=0){
					SharedPreferences mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
					Editor edit = mSp.edit();
					edit.putInt(FoneConstant.COLLETION_TV_UPDATE_COUNT, followsCount);
					edit.commit();
				}
			};
		}.start();
	}
	
	
	/**
	 * 是否收到过该通知
	 * @param id
	 * @return
	 */
	private static boolean isReceived(String id){
		L.v(TAG,"isReceived"," id : " + id);
		return StorageModule.getInstance().getNotificationByServerId(id)!=null;
	}
	
	// 判断是否可以发送到系统栏
	public boolean isSendTime() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		return!(hour >=0 && hour <=6);
	}

	
	/**
	 * 清除默认设置
	 */
	public void clearDefault() {

		boolean flag = getClearDefaultFlag();
		L.v(TAG, "clearDefault clearDefault flag: ", flag);

		if (flag) {// 如果服务器开关为开，才清除默认设置
			FoneUtil.resetDefaultSetting(mContext, classname);
		}
		L.v(TAG, "clearDefault", "isClearDefaultSetting :"
				+ FoneConstant.isClearDefaultSetting);
		if (FoneConstant.isClearDefaultSetting) { // 已经清除默认设置
			FoneConstant.isClearDefaultSetting = false;
		}
	}
	
	
	/**
	 * 获取清除默认开关标识
	 * @param context
	 * @return
	 */
	public boolean getClearDefaultFlag() {
		mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
		boolean flag = mSp.getBoolean(CLEAR_AUTO_FLAG, true);
		return flag;
	}
	
	/**
	 * 设置清除默认开关标识
	 * @param context
	 * @param flag
	 */
	public void setClearDefualtFlag(boolean flag) {
		mSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_NAME_SP,Context.MODE_PRIVATE);
			mSp.edit().putBoolean(CLEAR_AUTO_FLAG, flag).commit();
	}
	
	/**
	 * 发送外部通知 (外部通知受服务器及用户本地控制)
	 * 
	 * @return void
	 * @throws
	 */
	public void sendNotification(NotificationBean ni,Bitmap notificationImage) {

		L.v(TAG, "sendNotification", " start -------- ");
		
		String mNotifyTitle,mNotifyContent;
		
		mNotifyTitle = ni.getNotificationName(); // 通知标题
		mNotifyContent = ni.getNotificationContent(); // 通知内容
		
		FoneUtil.writeNotificationLog("发送外通知 : " + mNotifyTitle);
		
		RemoteViews views = null;
		RemoteViews videoView = null;
		
		views = new RemoteViews(mContext.getPackageName(),
				R.layout.outside_notification_view);
		videoView = new RemoteViews(mContext.getPackageName(),
				R.layout.outside_notification_video_view);
		
		initNotification(mNotifyTitle, mNotifyContent,views,videoView);
		
		// 针对3.0以下版本通知
		@SuppressWarnings("deprecation")
		Notification notification = new Notification(R.drawable.icon,
				mNotifyTitle, System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL; // 点击通知后取消
		notification.defaults |= Notification.DEFAULT_VIBRATE;// 震动提示
		notification.defaults = Notification.DEFAULT_SOUND
				| Notification.DEFAULT_LIGHTS; // 声音,Led提示
		
		
		// 针对3.0以上的通知
		NotificationCompat.Builder mBuilder = new Builder(mContext);
		mBuilder.setSmallIcon(R.drawable.icon);
		mBuilder.setContentText(mNotifyTitle);
		mBuilder.setDefaults(Notification.DEFAULT_SOUND);
		mBuilder.setAutoCancel(true);

		Intent notificationIntent = null;
				
		L.v(TAG, "sendNotification", " notification is open !! ");
		
			notificationIntent = new Intent();
			
			//设置传递内容
			notificationIntent.putExtra(NotificationReceiver.NOTIFICATION_INFO, ni);
			
			//设置展现形式
			int showType = ni.getNotificationContentPatternType();
			L.v(TAG, "sendNotification", " notification content pattern type : " + showType);
			if(showType==NotificationBean.NOTIFICATION_CONTENT_PATTERN_TYPE_IMAGE_TEXT){//图片+文字
				if(notificationImage!=null){
					L.i(TAG, "sendNotification", " notificationImage is exist ");
					videoView.setImageViewBitmap(R.id.notification_icon_iv, notificationImage);
				}
				L.i(TAG, "sendNotification", " notificationImage is exist ");
				notification.contentView = videoView;
				mBuilder.setContent(videoView);
			}else{//纯文字
				notification.contentView = views;
				mBuilder.setContent(views);
			}
			
			//根据连接类型 分类不同广播 
			int jumpType = ni.getNotificationExternalType();
			L.v(TAG, "sendNotification"," jumpType : " + jumpType);
			switch (jumpType) {
			case FULLSCREEN:
				// 全屏播放
				L.v(TAG, "sendNotification switch "," ---> FULLSCREEN");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_FULLSCREEN);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case DETAILVIEW:
				// 详情页
				L.v(TAG, "sendNotification switch "," ---> DETAILVIEW");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_DETAIL);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case WAP:
				// 打开wap网页
				L.v(TAG, "sendNotification switch "," ---> WAP");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_WAP);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case DOWNLOADSOFT:
				// 软件推荐
				L.v(TAG, "sendNotification switch "," ---> DOWNLOADSOFT");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_DOWNLOADSOFT);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case FEEPAGE:
				// 打开计费
				L.v(TAG, "sendNotification switch "," ---> FEEPAGE");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_FEE);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case PROGRAM:
				// 栏目页
				L.v(TAG, "sendNotification switch "," ---> PROGRAM");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_PROGRAM);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case WEBVIEW:
				// 视频原始网页
				L.v(TAG, "sendNotification switch "," ---> WEBVIEW");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_WEB);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;
			case FEEDBACK:
				//反馈回复页
				L.v(TAG, "sendNotification switch "," ---> FEEDBACK");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_FEEDBACK);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;

			case NOTIFITIONVIEW:
				//通知页面
				L.v(TAG, "sendNotification switch "," ---> NOTIFITIONVIEW");
				notificationIntent.setAction(NotificationReceiver.NOTIFICATION_NOTIFICATIONVIEW);
				notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				break;

			default:
				// 默认通知 点击后取消(不做跳转)
				L.v(TAG, "sendNotification switch "," ---> other ");
				notificationIntent = null;
				break;
			}
			
		if (notificationIntent != null) {
			Random r=new Random();
			int tmpID =r.nextInt(1000000000);
			L.i(TAG, "sendNotification",""+tmpID);
			
			PendingIntent contentItent = PendingIntent.getBroadcast(
					mContext, tmpID, notificationIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			notification.contentIntent = contentItent;
			mBuilder.setContentIntent(contentItent);
			
			if (android.os.Build.VERSION.SDK_INT <= 10) {
				// 通知的ID不能写死
				nm.notify(tmpID, notification);
			} else {
				nm.notify(tmpID, mBuilder.build());
			}
			FoneUtil.writeNotificationLog("已发送外通知  "+ ni.getNotificationName() +" 通知tmpID : " + tmpID);
		}
		
	}

	
	/**
	 * 初始化通知信息
	 */
	private void initNotification(String mNotifyTitle, String mNotifyContent,RemoteViews views,RemoteViews videoView) {

		// videoView.
		views.setTextViewText(R.id.notification_title_tv, mNotifyTitle);
		views.setTextViewText(R.id.notification_content_tv, mNotifyContent);
		
		videoView.setTextViewText(R.id.notification_title_tv, mNotifyTitle);
		videoView.setTextViewText(R.id.notification_content_tv, mNotifyContent);
		
		//直接读取圆角矩形图片
		Bitmap iconBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon);
		views.setImageViewBitmap(R.id.notification_icon_iv, iconBitmap);
		
//		// 处理圆角图片
//		BitmapDrawable bitmapDrawable = (BitmapDrawable) mContext
//				.getResources().getDrawable(R.drawable.logo_120);
//		views.setImageViewBitmap(R.id.notification_icon_iv, RoundImageUtil
//				.getRoundedCornerSquareBitmap(bitmapDrawable.getBitmap()));
	}

	/**
	 * 获取影视快讯通知的icon
	 * 
	 * @param imageUrl
	 */
	private Bitmap getIconImage(String imageUrl) {
		L.v(TAG, "getIconImage", "getImage url: " + imageUrl);
		if (imageUrl.trim().equals("") || imageUrl == null) {
			return null;
		}
		InputStream in = null;
		try {
			DefaultHttpClient client = null;

			
			HttpGet request = new HttpGet(imageUrl);
//			client = ApnUtils.createHttpClient(
//					mContext.getApplicationContext(), 5000, 12000);
			
			client = new DefaultHttpClient(); 
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 12000);
			HttpResponse response = client.execute(request);
			L.v(TAG, "getImage getResponseCode(): ", response.getStatusLine()
					.getStatusCode());
			FoneUtil.writeNotificationLog("getImage getResponseCode(): "+response.getStatusLine()
					.getStatusCode());

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				in = entity.getContent();
				
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;
				Bitmap bitmapIcon = BitmapFactory.decodeStream(
						in, null, options);
				return bitmapIcon;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}
